// 游戏状态变量
let gameState = {
    playerScore: 0,
    computerScore: 0,
    totalGames: 0,
    history: []
};

// DOM元素
const playerScoreEl = document.getElementById('player-score');
const computerScoreEl = document.getElementById('computer-score');
const totalGamesEl = document.getElementById('total-games');
const winRateEl = document.getElementById('win-rate');
const playerSelectionEl = document.getElementById('player-selection');
const computerSelectionEl = document.getElementById('computer-selection');
const resultEl = document.getElementById('result');
const historyListEl = document.getElementById('history-list');
const choiceBtns = document.querySelectorAll('.choice-btn');
const resetBtn = document.getElementById('reset-game');

// 游戏选项
const choices = {
    rock: { name: '石头', emoji: '✊' },
    paper: { name: '剪刀', emoji: '✋' },
    scissors: { name: '布', emoji: '✌️' }
};

// 初始化游戏
function initGame() {
    // 加载保存的游戏数据
    loadGameData();
    
    // 更新显示
    updateDisplay();
    
    // 添加事件监听器
    choiceBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const playerChoice = btn.getAttribute('data-choice');
            playGame(playerChoice);
        });
    });
    
    resetBtn.addEventListener('click', resetGame);
    
    // 添加键盘支持
    document.addEventListener('keydown', (e) => {
        if (e.key === '1' || e.key === 'r' || e.key === 'R') {
            playGame('rock');
        } else if (e.key === '2' || e.key === 'p' || e.key === 'P') {
            playGame('paper');
        } else if (e.key === '3' || e.key === 's' || e.key === 'S') {
            playGame('scissors');
        } else if (e.key === 'Escape') {
            resetGame();
        }
    });
}

// 生成电脑随机选择
function getComputerChoice() {
    const choiceKeys = Object.keys(choices);
    const randomIndex = Math.floor(Math.random() * choiceKeys.length);
    return choiceKeys[randomIndex];
}

// 判断游戏结果
function determineWinner(playerChoice, computerChoice) {
    if (playerChoice === computerChoice) {
        return 'tie';
    }
    
    if (
        (playerChoice === 'rock' && computerChoice === 'scissors') ||
        (playerChoice === 'paper' && computerChoice === 'rock') ||
        (playerChoice === 'scissors' && computerChoice === 'paper')
    ) {
        return 'win';
    }
    
    return 'lose';
}

// 播放游戏
function playGame(playerChoice) {
    const computerChoice = getComputerChoice();
    const result = determineWinner(playerChoice, computerChoice);
    
    // 更新游戏状态
    gameState.totalGames++;
    
    if (result === 'win') {
        gameState.playerScore++;
    } else if (result === 'lose') {
        gameState.computerScore++;
    }
    
    // 添加到历史记录
    const historyItem = {
        playerChoice,
        computerChoice,
        result,
        timestamp: new Date().toLocaleTimeString()
    };
    gameState.history.unshift(historyItem);
    
    // 限制历史记录数量
    if (gameState.history.length > 20) {
        gameState.history.pop();
    }
    
    // 更新显示
    updateDisplay();
    animateChoices(playerChoice, computerChoice, result);
    
    // 保存游戏数据
    saveGameData();
}

// 更新显示
function updateDisplay() {
    playerScoreEl.textContent = gameState.playerScore;
    computerScoreEl.textContent = gameState.computerScore;
    totalGamesEl.textContent = gameState.totalGames;
    
    // 计算胜率
    const winRate = gameState.totalGames > 0 
        ? Math.round((gameState.playerScore / gameState.totalGames) * 100)
        : 0;
    winRateEl.textContent = `${winRate}%`;
    
    // 更新历史记录
    updateHistoryList();
}

// 更新历史记录列表
function updateHistoryList() {
    if (gameState.history.length === 0) {
        historyListEl.innerHTML = '<p class="no-history">暂无游戏记录</p>';
        return;
    }
    
    historyListEl.innerHTML = '';
    
    gameState.history.forEach(item => {
        const historyItemEl = document.createElement('div');
        historyItemEl.className = `history-item ${item.result}`;
        
        let resultText = '';
        if (item.result === 'win') {
            resultText = '胜利';
        } else if (item.result === 'lose') {
            resultText = '失败';
        } else {
            resultText = '平局';
        }
        
        historyItemEl.innerHTML = `
            <div><strong>时间:</strong> ${item.timestamp}</div>
            <div>
                <strong>你:</strong> ${choices[item.playerChoice].name} ${choices[item.playerChoice].emoji} vs 
                <strong>电脑:</strong> ${choices[item.computerChoice].name} ${choices[item.computerChoice].emoji}
            </div>
            <div><strong>结果:</strong> ${resultText}</div>
        `;
        
        historyListEl.appendChild(historyItemEl);
    });
}

// 动画显示选择结果
function animateChoices(playerChoice, computerChoice, result) {
    // 显示选择
    playerSelectionEl.innerHTML = `<span>${choices[playerChoice].emoji}</span>`;
    computerSelectionEl.innerHTML = `<span>${choices[computerChoice].emoji}</span>`;
    
    // 添加动画效果
    playerSelectionEl.classList.add('animate-selection');
    computerSelectionEl.classList.add('animate-selection');
    
    // 显示结果文本
    let resultText = '';
    let resultColor = '';
    
    if (result === 'win') {
        resultText = '🎉 恭喜你赢了！';
        resultColor = '#28a745';
    } else if (result === 'lose') {
        resultText = '😢 很遗憾你输了！';
        resultColor = '#dc3545';
    } else {
        resultText = '🤝 平局！再来一局！';
        resultColor = '#ffc107';
    }
    
    resultEl.innerHTML = `<p style="color: ${resultColor};">${resultText}</p>`;
    
    // 移除动画类
    setTimeout(() => {
        playerSelectionEl.classList.remove('animate-selection');
        computerSelectionEl.classList.remove('animate-selection');
    }, 500);
}

// 重置游戏
function resetGame() {
    if (confirm('确定要重置游戏吗？所有记录将会清除。')) {
        gameState = {
            playerScore: 0,
            computerScore: 0,
            totalGames: 0,
            history: []
        };
        
        // 重置显示
        playerSelectionEl.innerHTML = '<span class="placeholder">等待选择</span>';
        computerSelectionEl.innerHTML = '<span class="placeholder">?</span>';
        resultEl.innerHTML = '<p>选择一个选项开始游戏</p>';
        
        updateDisplay();
        saveGameData();
    }
}

// 保存游戏数据到本地存储
function saveGameData() {
    localStorage.setItem('rockPaperScissorsGame', JSON.stringify(gameState));
}

// 从本地存储加载游戏数据
function loadGameData() {
    const savedData = localStorage.getItem('rockPaperScissorsGame');
    if (savedData) {
        gameState = JSON.parse(savedData);
    }
}

// 添加CSS动画样式
document.head.insertAdjacentHTML('beforeend', `
    <style>
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        
        .animate-selection {
            animation: pulse 0.5s ease-in-out;
        }
    </style>
`);

// 当页面加载完成时初始化游戏
document.addEventListener('DOMContentLoaded', initGame);